// src/utils/axiosInstance.ts
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();

const axiosInstance = axios.create({
  baseURL: '/api',
  timeout: 10000
});

// 请求拦截器：添加token到请求头
axiosInstance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器：处理认证错误和数据提取
axiosInstance.interceptors.response.use(
  (response) => {
    // 直接返回响应中的data字段
    return response.data;
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      router.push('/login');
    }
    return Promise.reject(error);
  }
);

export default axiosInstance;